package com.xhsj.user.utils;//package com.xhsj.badges.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xhsj.user.security.entity.LoginUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;

import java.util.Map;


/**
 * 用户工具类
 */
public class UserUtils {

    /**
     * 获取当前登录用户
     * @author 苏小林
     * @date 2019/11/19 9:06
     * @return:
     */
    @SuppressWarnings("rawtypes")
    public static LoginUser getLoginAppUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication instanceof OAuth2Authentication) {
            OAuth2Authentication oAuth2Auth = (OAuth2Authentication) authentication;
            authentication = oAuth2Auth.getUserAuthentication();

            Object principal = authentication.getPrincipal();
            if (principal instanceof LoginUser){
                return (LoginUser) principal;
            }

            Object details = authentication.getDetails();
            if (details instanceof Map) {
                Map deta = (Map) authentication.getDetails();
                Map map = (Map) deta.get("principal");
                LoginUser loginUser =  JSONObject.toJavaObject((JSON) JSON.toJSON(map),LoginUser.class);
                return loginUser;
            }



        }

        return null;
    }
}
